/**
 * fileName: YLES_CLIENT_TOOL
 * @NApiVersion 2.1
 */

import crd = require("N/currentRecord");
import record = require("N/record");
import search = require("N/search");
import runtime = require("N/runtime");
import {ObjectJson} from "./YLES_SEARCH_TOOL";
// @ts-ignore
import * as Papa from "./papaparse";
const subInfo = {sublistId: 'info_list'};

/**
 *  更改页数
 *  @param num - 跳转的页数（基于当前界面 +n -n）
 */
export function changeMyPageIndex(num: number) {
    const rec = crd.get();
    const nowPage = rec.getValue('current_page') as number;
    let url = window.location.href;
    url = changeURLArg(url, 'nowPage', nowPage + num);
    window.onbeforeunload = null;
    window.location.href = url;
}

/**
 * 更改每页显示行数
 * @param rec - 当前记录
 */
export function changePageNo(rec: record.ClientCurrentRecord) {
    const pageNo = rec.getValue('lines_page') as number;
    let url = window.location.href;
    url = changeURLArg(url, 'pageNo', pageNo);
    url = changeURLArg(url, 'nowPage', 1);
    window.onbeforeunload = null;
    window.location.href = url;
}

//替换链接中的值
export function changeURLArg(targetUrl: string, arg: string, arg_val: string | number | null) {
    let pattern = arg + '=([^&]*)';
    let replaceText = arg + '=' + arg_val;
    if (targetUrl.match(pattern)) {
        let tmp = '/(' + arg + '=)([^&]*)/gi';
        tmp = targetUrl.replace(eval(tmp), replaceText);
        return tmp;
    } else {
        if (targetUrl.match('[\?]')) {
            return targetUrl + '&' + replaceText;
        } else {
            return targetUrl + '?' + replaceText;
        }
    }
}

/**
 * 界面选择按钮
 * @param num - 是否限制行数
 * @param val - 勾选或者不勾选
 */
export function markMyAll(val: boolean, num?: number) {
    const rec = crd.get();

    const cnt = rec.getLineCount({...subInfo});
    for (let i = 0; i < cnt; i++) {
        if (num && i >= num) return;

        rec.selectLine({...subInfo, line: i});
        rec.setCurrentSublistValue({...subInfo, fieldId: 'line_check', value: val});
        rec.commitLine({...subInfo});
    }
}


//依据界面信息下载导出CSV
export function exportMyCSV() {
    const curRec = crd.get();
    const sublist_fields = JSON.parse(curRec.getValue({fieldId: 'sublist_fields'}) as string);
    const cnt = curRec.getLineCount({...subInfo});
    const csvData = [];
    for (let i = 0; i < cnt; i++) {
        const dd: ObjectJson = {};
        sublist_fields.map(function (sf: ObjectJson) {
            let vv = curRec.getSublistValue({...subInfo, fieldId: sf.id as string, line: i}) as string || '';
            vv = String(vv).replace(/<\/{0,1}p>/g, '');
            dd[sf.label as string] = vv;
        });
        // if(fail || dd.msg == 'This item have been inactived.'){
        csvData.push(dd);
        // }
    }
    const fields = sublist_fields.map(function (sf: ObjectJson) {
        return sf.label
    });
    const csv_content = Papa.unparse(csvData, {columns: fields});
    exeDownLoad(csv_content, 'export_data.csv');
}


//执行下载
function exeDownLoad(content: string, fileName: string) {
    const data = "\ufeff" + content;
    const aEle = document.createElement("a");// 创建a标签
    const blob = new Blob([data], {type: 'text/csv,charset=UTF-8'});
    aEle.download = fileName;// 设置下载文件的文件名
    aEle.href = URL.createObjectURL(blob);
    aEle.click();// 设置点击事件
}

let bartimer = 0;
//添加屏幕遮罩，黑屏
export function addScreenDisabled() {
    var $ = jQuery;
    var docHeight = $(document).height() as number; //获取窗口高度
    $('body').append('<div id="overlay"></div>');
    $('#overlay').append(`
        <div id="screen_ck_id" style="width:100%;height:100%;line-height:700px;text-align:center;display:block;font-weight: bold; color: red">
             文件校验中，请勿刷新界面...
        </div>`);
    $('#overlay')
        .height(docHeight)
        .css({
            'opacity': .6, //透明度
            'position': 'absolute',
            'top': 0,
            'left': 0,
            'background-color': '#939090',
            'width': '100%',
            'z-index': 10000 //保证这个悬浮层位于其它内容之上
        });
    //initProgress();
    //window.location.reload();
    // setTimeout(function(){$('#overlay').fadeOut('slow')}, 10000000);
}


//启动导入进度条
export function initCSVProgress() {
    //清除所有定时器
    if (bartimer > 0) {
        clearInterval(bartimer);
    }

    //重新启用定时器
    bartimer = window.setInterval(function(){setProcess();},2000);
    function setProcess() {
        try{
            let logSts = '3',dealNos = 0;
            const crd = require("N/currentRecord");
            const search = require("N/search");
            const cur_rec = crd.get();
            const logId = String(cur_rec.getValue('import_log_id'));
            const totalNum = Number(cur_rec.getValue('ck_success_line'));

            //获取导入的数据条数
            const ckiSearch = search.create({
                type: 'customrecord_lyes_head_item_barcode',
                filters: [
                    ['custrecord_yles_import_log','anyof',logId]
                ],
                columns: [
                    {name:'custrecord_yles_status',join:'custrecord_yles_import_log',summary:search.Summary.GROUP,sort:search.Sort.ASC},
                    {name:'id',join:'custrecord_yles_head',summary:search.Summary.COUNT},
                ]
            });
            const data = ckiSearch.run().getRange({start:0,end:1});
            if (data && data.length > 0) {
                logSts = data[0].getValue(ckiSearch.columns[0]) as string;
                dealNos = Number(data[0].getValue(ckiSearch.columns[1]) as string);
            }
            if (logSts == '3') {
                logSts = search.lookupFields({
                    type: 'customrecord_yles_import_csv_log',
                    id: logId,
                    columns: ['custrecord_yles_status']
                })['custrecord_yles_status'][0].value;
            }
            // console.log('logSts',logSts);
            // console.log('dealNos',dealNos);
            // console.log('totalNum',totalNum);
            //导入中才显示进度条
            if (logSts == '3') {
                const percent = dealNos / totalNum;
                if (percent <= 0) {
                    /*// @ts-ignore
                    jQuery('#import_csv_progress').LineProgressbar({
                        percentage: 0,
                        fillBackgroundColor: '#e67e22',
                        height: '25px',
                        radius: '15px'
                    });*/
                }
                else if (percent < 0.5) {
                    // @ts-ignore
                    jQuery('#import_csv_progress').LineProgressbar({
                        percentage: percent * 100,
                        fillBackgroundColor: '#e67e22',
                        height: '25px',
                        radius: '15px'
                    });
                }else if (percent < 0.8) {
                    // @ts-ignore
                    jQuery('#import_csv_progress').LineProgressbar({
                        percentage: percent * 100,
                        fillBackgroundColor: '#1abc9c',
                        height: '25px',
                        radius: '15px'
                    });
                }else if (percent <= 0.99) {
                    // @ts-ignore
                    jQuery('#import_csv_progress').LineProgressbar({
                        percentage: percent * 100,
                        fillBackgroundColor: '#1abc9c',
                        height: '25px',
                        radius: '15px'
                    });
                    // window.clearInterval(bartimer);
                }
            }else {
                // @ts-ignore
                jQuery('#import_csv_progress').LineProgressbar({
                    percentage: 100,
                    fillBackgroundColor: '#1abc9c',
                    height: '25px',
                    radius: '15px'
                });
                window.onbeforeunload = null;
                window.clearInterval(bartimer);
                window.location.reload();
            }
        }catch (erxp) {
            console.log('setProcess',erxp);
            //@ts-ignore
            if (erxp.name == 'SCRIPT_EXECUTION_USAGE_LIMIT_EXCEEDED') {
                window.onbeforeunload = null;
                window.clearInterval(bartimer);
                window.location.reload();
            }
        }
    }
}

//启动导入进度条
export function initCheckCSVProgress() {
    //清除所有定时器
    if (bartimer > 0) {
        clearInterval(bartimer);
    }

    //重新启用定时器
    bartimer = window.setInterval(function(){setProcess();},3000);
    function setProcess() {
        try{
            let logSts = '2';
            const runtime = require("N/runtime");
            const search = require("N/search");
            const cur_rec = crd.get();
            const logId = cur_rec.getValue('import_log_id') as string;
            const totalNum = Number(cur_rec.getValue('total_line'));
            const ckd_line = cur_rec.getValue('ckd_line');
            const logInfos = search.lookupFields({
                type: 'customrecord_yles_import_csv_log',
                id: logId,
                columns: ['custrecord_yles_status','custrecord_yles_ckd_line_no']
            });
            const dealNos = logInfos['custrecord_yles_ckd_line_no'];
            logSts = logInfos['custrecord_yles_status'][0].value;

            //校验中才显示进度条
            if (logSts == '2') {
                const percent = dealNos / totalNum;
                // console.log('percent',percent);
                if (percent <= 0) {
                    /*// @ts-ignore
                    jQuery('#import_csv_progress').LineProgressbar({
                        percentage: 0,
                        fillBackgroundColor: '#e67e22',
                        height: '25px',
                        radius: '15px'
                    });*/
                }
                else if (percent < 0.5) {
                    // @ts-ignore
                    jQuery('#check_csv_progress').LineProgressbar({
                        percentage: percent * 100,
                        fillBackgroundColor: '#e67e22',
                        height: '25px',
                        radius: '15px'
                    });
                }else if (percent < 0.8) {
                    // @ts-ignore
                    jQuery('#check_csv_progress').LineProgressbar({
                        percentage: percent * 100,
                        fillBackgroundColor: '#1abc9c',
                        height: '25px',
                        radius: '15px'
                    });
                }else if (percent <= 0.99) {
                    // @ts-ignore
                    jQuery('#check_csv_progress').LineProgressbar({
                        percentage: percent * 100,
                        fillBackgroundColor: '#1abc9c',
                        height: '25px',
                        radius: '15px'
                    });
                    // window.clearInterval(bartimer);
                }
            }else {
                // @ts-ignore
                jQuery('#check_csv_progress').LineProgressbar({
                    percentage: 100,
                    fillBackgroundColor: '#1abc9c',
                    height: '25px',
                    radius: '15px'
                });
                window.onbeforeunload = null;
                window.clearInterval(bartimer);
                window.location.reload();
            }
        }catch (erxp) {
            console.log('setProcess',erxp);
            //@ts-ignore
            if (erxp.name == 'SCRIPT_EXECUTION_USAGE_LIMIT_EXCEEDED') {
                window.onbeforeunload = null;
                window.clearInterval(bartimer);
                window.location.reload();
            }
        }
    }
}

function todoTest() {
    search.load({id:''});
    runtime.getCurrentUser().id;
}